import React, {useState} from "react";
import {
  Card,
  CardHeader,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  InputAdornment,
  ListItemIcon,
  OutlinedInput,
  Snackbar
} from "@material-ui/core";
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import SearchIcon from '@material-ui/icons/Search';
import IconButton from "@material-ui/core/IconButton";
import MoreVertIcon from '@material-ui/icons/MoreVert';
import {useSelector} from "react-redux";
import Divider from "@material-ui/core/Divider";
import EqualizerIcon from '@material-ui/icons/Equalizer';
import DeleteIcon from '@material-ui/icons/Delete';
import CloseIcon from '@material-ui/icons/Close';
import {indicatorResponseToQueryWrapper} from "../../../../ruleEngine/rulesGenerator";
import Backend from "../../../Backend/Backend";
import parse from "html-react-parser";
import PreviewIndicator from "./PreviewIndicator";
import LinkIcon from '@material-ui/icons/Link';

const borderRadius = "12px 4px 12px 4px";

export default function MyQuestions() {
  const userQuestionsAndIndicators = useSelector(state => state.gqiEditor.common.userQuestionAndIndicators);
  const darkModeSelected = useSelector((state) => state.commonSettings.darkMode);
  const [hover, setHover] = useState(-1);
  const [openDetails, setOpenDetails] = React.useState(false);
  const [visData, setVisData] = useState([]);
  const [search, setSearch] = useState("");
  const [questionName, setQuestionName] = useState("");
  const [questions, setQuestions] = useState(userQuestionsAndIndicators);
  const [loading, setLoading] = useState(false);

  // TODO: For the future: Create a Checkbox filtering for question according to the type of indicators
  // const filterQuestionByIndicatorType = (event) => {
  //   console.log(event.target.id);
  // };

  const handleVisualization = async (question) => {
    let visArray = [];
    setLoading(true);
    question.indicators.forEach(i => {
      let vizQuery = indicatorResponseToQueryWrapper(i);
      // TODO: Update with async method
      Backend.post("/AnalyticsEngine/GetIndicatorPreview", vizQuery)
        .then(response => {
          let unescapedVizCode = decodeURIComponent(response.data.visualizationCode);
          let objectData = parse(unescapedVizCode);
          let scriptData = objectData[1].props.dangerouslySetInnerHTML.__html;
          visArray.push({name: i.name, objectData, scriptData});
          setLoading(false);
        }, (error) => {
          // TODO: Add a feedback
          console.log(error);
        })
    })
    setVisData(visArray);
    setQuestionName(question.question.name);
  }

  const searchQuestions = (e) => {
    setSearch(e.target.value);
    let qiArray = [];
    userQuestionsAndIndicators.forEach(qi => {
      if (qi.question.name.match(e.target.value)) {
        qiArray.push(qi);
      }
    })
    setQuestions(qiArray);
  }

  return (
    <>
      <Card style={{marginBottom: 32, borderRadius: borderRadius}}>
        <Grid container direction="column">
          <Grid item xs>
            <CardHeader
              action={<Button variant="contained" color="primary" style={{borderRadius: borderRadius}}> Create
                Question </Button>}
              title={<Typography> Create a new question </Typography>}/>
          </Grid>
        </Grid>
      </Card>

      <Grid container alignItems="center" style={{marginBottom: 24}} spacing={2}>
        <Grid item xs>
          <OutlinedInput size="small" id="outlined-adornment-weight" value={search} placeholder="Search for questions"
                         onChange={searchQuestions}
                         endAdornment={<InputAdornment position="end"> <SearchIcon color="disabled"/> </InputAdornment>}
                         aria-describedby="outlined-weight-helper-text"
                         inputProps={{"aria-label": "weight"}} color="primary"
                         style={{
                           width: 300, borderRadius: borderRadius,
                           backgroundColor: !darkModeSelected ? '#fff' : ''
                         }}/>
        </Grid>
        {/* TODO: For the future: When other types of indicators are developed */}
        {/*<Grid item>*/}
        {/*  <FormGroup>*/}
        {/*    <Grid container alignItems="center">*/}
        {/*      <Typography style={{marginRight: 8}}> Filter by Indicator type: </Typography>*/}
        {/*      <FormControlLabel*/}
        {/*        label="Basic"*/}
        {/*        control={<Checkbox id="1" color="primary" defaultChecked onChange={filterQuestionByIndicatorType}/>}*/}
        {/*      />*/}
        {/*      <FormControlLabel*/}
        {/*        label="Composite"*/}
        {/*        control={<Checkbox id="2" color="primary" defaultChecked onChange={filterQuestionByIndicatorType}/>}/>*/}
        {/*      <FormControlLabel*/}
        {/*        label="Multi-level"*/}
        {/*        control={<Checkbox id="3" color="primary" defaultChecked onChange={filterQuestionByIndicatorType}/>}/>*/}
        {/*    </Grid>*/}
        {/*  </FormGroup>*/}
        {/*</Grid>*/}
      </Grid>

      <Grid container justify="space-between" style={{marginBottom: 8}}>
        <Typography style={{fontWeight: "bold"}}> List of my questions </Typography>
        <Typography> {questions.length} questions found </Typography>
      </Grid>

      {questions.map((q, index) => {
        return (
          <>
            <Card key={index} style={{marginBottom: 8, borderRadius: borderRadius}} raised={index === hover}
                  onMouseEnter={() => setHover(index)}
                  onMouseLeave={() => setHover(-1)}>
              <Grid container direction="column">
                <Grid item xs>
                  <CardHeader action={<OptionsForQuestion q={q} handleVisualization={handleVisualization}
                                                          openDetails={openDetails} setOpenDetails={setOpenDetails}/>}
                              title={<Typography> {q.question.name} </Typography>}/>
                </Grid>
              </Grid>
            </Card>

          </>
        );
      })}

      {/* Modal to preview the indicators specified for the question*/}
      <Dialog fullWidth maxWidth="md" open={openDetails} onClose={() => setOpenDetails(!openDetails)}
              aria-labelledby="form-dialog-title">
        <DialogTitle id="form-dialog-title"> {questionName} </DialogTitle>
        {!loading ? <>
          <DialogContent>
            <Grid container justify="center" alignItems="center">
              {visData.map((viz, index) => <PreviewIndicator key={index} viz={viz} card={true}/>)}
            </Grid>
          </DialogContent>
        </> : <Grid container direction="column" alignItems="center" style={{marginTop: 32}}>
          <CircularProgress style={{marginBottom: 8}}/>
          <Typography> Loading indicators </Typography>
        </Grid>}
        <DialogActions>
          <Button onClick={() => setOpenDetails(!openDetails)}> Close </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}

// A separate component for menu is required for correct item when onClick action is triggered.
// Read more: https://stackoverflow.com/questions/58041935/material-ui-menu-component-only-last-menuitem-onclick-action-is-triggered
const OptionsForQuestion = ({q, handleVisualization, openDetails, setOpenDetails}) => {
  const [openMenu, setOpenMenu] = useState(null);
  const [copiedCode, setCopiedCode] = useState(false);

  const copyQuestionCode = (question) => {
    const {questionCode} = question;
    navigator.clipboard.writeText(questionCode).then(() => {
      setCopiedCode(!copiedCode);
      setOpenMenu(null);
    });
  }

  return (
    <>
      <IconButton onClick={(e) => {
        handleVisualization(q);
        setOpenMenu(e.currentTarget);
      }}>
        <MoreVertIcon/>
      </IconButton>

      <Menu anchorEl={openMenu} keepMounted open={Boolean(openMenu)}
            onClose={() => setOpenMenu(null)} getContentAnchorEl={null}
            anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}
            transformOrigin={{vertical: 'top', horizontal: 'right'}}>

        <MenuItem onClick={() => {
          setOpenDetails(!openDetails);
          setOpenMenu(null);
        }}>
          <ListItemIcon> <EqualizerIcon/> </ListItemIcon>
          <Typography variant="inherit" noWrap> Show question </Typography>
        </MenuItem>

        <MenuItem style={{margin: "8px 0 8px 0"}} onClick={() => copyQuestionCode(q)}>
          <ListItemIcon> <LinkIcon/> </ListItemIcon>
          <Typography variant="inherit" noWrap> Embed code </Typography>
        </MenuItem>

        <Divider style={{margin: "8px 0 8px 0"}}/>

        <MenuItem onClick={() => setOpenMenu(null)}>
          <ListItemIcon> <DeleteIcon color="secondary"/> </ListItemIcon>
          <Typography variant="inherit" noWrap> Delete </Typography>
        </MenuItem>
      </Menu>

      <Snackbar
        anchorOrigin={{vertical: "bottom", horizontal: "left"}}
        open={copiedCode}
        onClose={() => setCopiedCode(false)}
        autoHideDuration={3000}
        message="Code copied!"
        action={
          <IconButton size="small" aria-label="close" color="inherit" onClick={() => setCopiedCode(false)}>
            <CloseIcon fontSize="small"/>
          </IconButton>
        }
      />
    </>
  );
}

